﻿using AttendanceAccounting.Classes;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using TeacherLoad.Classes;

namespace AttendanceAccounting.Windows
{
    /// <summary>
    /// Логика взаимодействия для Students.xaml
    /// </summary>
    public partial class Students : Window
    {
        private bool _editMode = false;
        private static int _id = 0;
        private static Student _student;
        public Students()
        {
            InitializeComponent();
            DataStudent.DataContext = LoadData();
        }

        private List<Student> LoadData()
        {
            DataTable dataTable = SendToServer.GetStudents();
            List<Student> students = new List<Student>();
            if (dataTable.Rows.Count > 0)
            {
                foreach (DataRow row in dataTable.Rows)
                {
                    Student st = new Student(
                        Convert.ToInt32(row[0]),
                        row[1].ToString(),
                        row[2].ToString(),
                        row[3].ToString());
                    students.Add(st);
                }
            }
            return students;
        }

        private void AddStudent_Click(object sender, RoutedEventArgs e)
        {
            if (student_lastname.Text == string.Empty || student_firstname.Text == string.Empty)
            {
                MessageBox.Show("Укажите фамилию и имя", "Заполните обязательные поля",
                    MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }
            
            Student st = new Student(
                id: _id,
                lastname: student_lastname.Text,
                firstname: student_firstname.Text,
                patronymic: student_patronymic.Text
                );
            if (_editMode)
            {
                if (SendToServer.EditStudent(st))
                {
                    ClearText();
                    UpdateUi();
                    _editMode = false;
                }
                else
                {
                    MessageBox.Show("Ошибка записи", "Неудача",
                        MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            else
            {
                if (SendToServer.AddStudent(st))
                {
                    ClearText();
                }
                else
                {
                    MessageBox.Show("Ошибка записи", "Неудача",
                        MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }

            DataStudent.DataContext = LoadData();
        }

        private void ClearText()
        {
            // Очистка полей ввода (если запись была успешной)
            student_lastname.Clear();
            student_firstname.Clear();
            student_patronymic.Clear();

        }

        private void UpdateUi()
        {
            GroupHeader.Header = "Добавление нового студента";
            addStudent.Content = "Добавить студента";
        }

        private void EditRow_Click(object sender, RoutedEventArgs e)
        {
            if (listStudents.SelectedItems.Count > 0)

            {

                _editMode = true;   // Установка режима редактирования


                GroupHeader.Header = "Обновить данные";

                addStudent.Content = "Обновить";


                student_lastname.Text = _student.LastName;

                student_firstname.Text = _student.FirstName;

                student_patronymic.Text = _student.Patronymic;


                // Получаем идентификатор (id) выделенного читателя

                _id = _student.Id;

            }
        }

        private void listStudents_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (listStudents.SelectedItems.Count > 0)
            {
                _student = listStudents.SelectedItem as Student;
                infoLastName.Text = _student.LastName;
                infoFirstName.Text = _student.FirstName;
                infoPatronymic.Text = _student.Patronymic;
            }
        }

        private void ContextMenu_ContextMenuOpening(object sender, ContextMenuEventArgs e)
        {
            if (listStudents.SelectedItems.Count > 0)
            {
                EditRow.IsEnabled = true;
            }
            else
            {
                EditRow.IsEnabled = false;
            }
        }
    }
}
